import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Select, Space, message } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { useRequest } from 'ahooks';
import { TableRelation, RelationType, ConnectionInfo, TableColumn } from '@/types/nl2sql/type';
import nl2sqlService from '@/api/services/nl2sqlService';

interface BasicInfoEditModalProps {
  visible: boolean;
  onCancel: () => void;
  onOk: (values: any) => void;
  initialData: {
    table_description: string;
    table_primary_key: string;
    table_relations: TableRelation[] | null;
  } | null;
  tableName: string;
  connectionInfo: ConnectionInfo | null;
}

const BasicInfoEditModal: React.FC<BasicInfoEditModalProps> = ({
  visible,
  onCancel,
  onOk,
  initialData,
  tableName,
  connectionInfo,
}) => {
  const [form] = Form.useForm();
  const [relations, setRelations] = useState<TableRelation[]>([]);
  const [sourceColumns, setSourceColumns] = useState<TableColumn[]>([]);
  const [targetTables, setTargetTables] = useState<string[]>([]);
  const [targetColumnsMap, setTargetColumnsMap] = useState<Record<string, TableColumn[]>>({});

  // 获取来源表字段
  const { runAsync: fetchSourceColumns, loading: sourceColumnsLoading } = useRequest(
    async () => {
      if (!connectionInfo?.database_id) return [];
      
      // 从 connectionInfo 中找到当前表的 table_data_id
      const currentTable = connectionInfo.table_simple_infos?.find(
        table => table.table_name === tableName
      );
      
      if (!currentTable?.table_data_id) return [];
      
      const response = await nl2sqlService.searchTableColumns(currentTable.table_data_id, {
        isPage: false,
        offset: -1,
        page: 1,
        page_size: 1000,
      });
      
      return response?.table_info?.table_columns || [];
    },
    {
      manual: true,
      onSuccess: (data) => {
        setSourceColumns(data);
      },
      onError: (error) => {
        console.error('获取来源表字段失败:', error);
      },
    }
  );

  // 获取目标表列表
  const { runAsync: fetchTargetTables, loading: targetTablesLoading } = useRequest(
    async () => {
      if (!connectionInfo?.table_simple_infos) return [];
      
      // 直接从 connectionInfo 中获取所有表名，排除当前表
      const allTables = connectionInfo.table_simple_infos
        .map(table => table.table_name)
        .filter(name => name !== tableName); // 排除当前表
      
      return allTables;
    },
    {
      manual: true,
      onSuccess: (data) => {
        setTargetTables(data);
      },
      onError: (error) => {
        console.error('获取目标表列表失败:', error);
      },
    }
  );

  // 获取目标表字段
  const { runAsync: fetchTargetColumns, loading: targetColumnsLoading } = useRequest(
    async (tableName: string) => {
      if (!connectionInfo?.database_id || !tableName) return [];
      
      // 从 connectionInfo 中找到目标表的 table_data_id
      const targetTable = connectionInfo.table_simple_infos?.find(
        table => table.table_name === tableName
      );
      
      if (!targetTable?.table_data_id) return [];
      
      const response = await nl2sqlService.searchTableColumns(targetTable.table_data_id, {
        isPage: false,
        offset: -1,
        page: 1,
        page_size: 1000,
      });
      
      return response?.table_info?.table_columns || [];
    },
    {
      manual: true,
      onSuccess: (data, [tableName]) => {
        setTargetColumnsMap(prev => ({
          ...prev,
          [tableName]: data,
        }));
      },
      onError: (error) => {
        console.error('获取目标表字段失败:', error);
      },
    }
  );

  // 更新表信息
  const { runAsync: updateTable, loading: updateLoading } = useRequest(
    async (values: any) => {
      if (!connectionInfo?.schema_dataset || !connectionInfo?.table_simple_infos) {
        throw new Error('缺少必要的连接信息');
      }
      
      // 从 connectionInfo 中找到当前表的 table_data_id
      const currentTable = connectionInfo.table_simple_infos?.find(
        table => table.table_name === tableName
      );
      
      if (!currentTable?.table_data_id) {
        throw new Error('未找到当前表信息');
      }
      
      // 调用 updateTable 接口
      const response = await nl2sqlService.updateTable(
        connectionInfo.schema_dataset, // datasetId
        currentTable.table_data_id,    // tableId
        {
          table_name: tableName,
          table_description: values.table_description,
          table_primary_key: values.table_primary_key,
          table_relations: relations, // 使用 relations 状态变量，确保格式正确
          table_columns: sourceColumns, // 保持原有的列信息不变
        }
      );
      
      return response;
    },
    {
      manual: true,
      onSuccess: (response) => {
        message.success('基础信息更新成功');
        // 调用父组件的 onOk 回调
        onOk({
          table_description: form.getFieldValue('table_description'),
          table_primary_key: form.getFieldValue('table_primary_key'),
          table_relations: relations, // 使用 relations 状态变量，确保格式正确
        });
      },
      onError: (error) => {
        // message.error('基础信息更新失败');
        console.error('更新表信息失败:', error);
      },
    }
  );

  // 初始化表单数据
  useEffect(() => {
    if (visible && initialData) {
      const relations = initialData.table_relations || [];
      setRelations(relations);
      form.setFieldsValue({
        table_description: initialData.table_description,
        table_primary_key: initialData.table_primary_key,
        relations: relations,
      });
      
      // 为已有的表关系获取对应的目标表字段
      relations.forEach(relation => {
        if (relation.to_table_name) {
          fetchTargetColumns(relation.to_table_name);
        }
      });
    }
  }, [visible, initialData, form]);

  // 当弹窗显示时，获取数据
  useEffect(() => {
    if (visible && connectionInfo) {
      fetchSourceColumns();
      fetchTargetTables();
    }
  }, [visible, connectionInfo]);

  // 处理添加表关系
  const handleAddRelation = () => {
    const newRelation: TableRelation = {
      from_table_name: tableName,
      from_column_name: '',
      to_table_name: '',
      to_column_name: '',
      relation_type: null,
    };
    setRelations([...relations, newRelation]);
  };

  // 处理删除表关系
  const handleRemoveRelation = (index: number) => {
    const newRelations = relations.filter((_, i) => i !== index);
    setRelations(newRelations);
    form.setFieldValue('relations', newRelations);
  };

  // 处理表关系变化
  const handleRelationChange = (index: number, field: keyof TableRelation, value: any) => {
    const newRelations = [...relations];
    newRelations[index] = { ...newRelations[index], [field]: value };
    setRelations(newRelations);
    form.setFieldValue('relations', newRelations);

    // 当目标表变化时，获取对应的字段列表
    if (field === 'to_table_name' && value) {
      fetchTargetColumns(value);
    }
  };

  // 处理表单提交
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      
      // 校验表关系数据
      if (relations.length > 0) {
        for (let i = 0; i < relations.length; i++) {
          const relation = relations[i];
          console.log('relation', relation);
          if (!relation.from_column_name) {
            message.error(`${relation.from_table_name}的来源字段不能为空`);
            return;
          }
          if (!relation.to_table_name) {
            message.error(`${relation.from_table_name}的目标表不能为空`);
            return;
          }
          if (!relation.to_column_name) {
            message.error(`${relation.from_table_name}的目标表字段不能为空`);
            return;
          }
        }
      }
      
      // 调用 updateTable 接口
      await updateTable(values);
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  // 关系类型选项
  const relationTypeOptions = [
    { label: 'Many-to-one', value: 'Many-to-one' },
    { label: 'One-to-many', value: 'One-to-many' },
    { label: 'One-to-one', value: 'One-to-one' },
  ];

  return (
    <div className="p-6">
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          table_description: '',
          table_primary_key: '',
          relations: [],
        }}
      >
        {/* 数据表描述 */}
        <Form.Item 
          label="数据表描述" 
          name="table_description"
          rules={[
            { required: true, message: '请输入数据表描述' }
          ]}
        >
          <Input 
            placeholder="请输入数据表描述" 
            maxLength={200}
            showCount
          />
        </Form.Item>
        
        {/* 数据表主键 */}
        <Form.Item 
          label="数据表主建" 
          name="table_primary_key"
          rules={[
            { required: true, message: '请输入数据表主键' }
          ]}
        >
          <Select
            placeholder="请输入数据表主建"
            allowClear
            showSearch
            filterOption={(input, option) =>
              (option?.label?.toString() ?? '').toLowerCase().includes(input.toLowerCase())
            }
          >
            {sourceColumns.map(column => (
              <Select.Option key={column.column_name} value={column.column_name}>
                {column.column_name}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
        
        {/* 表关系 */}
        <Form.Item label="表关系">
          <div className="space-y-4">
            {/* 添加表关系按钮 */}
            <div className="flex justify-end">
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={handleAddRelation}
                className="bg-blue-600 hover:bg-blue-700"
              >
                添加表关系
              </Button>
            </div>

            {/* 表关系表格 */}
            <div className="border border-gray-200 rounded-lg overflow-hidden">
              <div className="bg-gray-50 px-4 py-3 border-b border-gray-200">
                <div className="grid grid-cols-5 gap-4 text-sm font-medium text-gray-700">
                  <div>来源表</div>
                  <div>来源字段</div>
                  <div>目标表</div>
                  <div>目标表字段</div>
                  <div>类型</div>
                </div>
              </div>
              
              <div className="divide-y divide-gray-200">
                {relations.map((relation, index) => (
                  <div key={index} className="px-4 py-3">
                    <div className="grid grid-cols-5 gap-4 items-center">
                      {/* 来源表 */}
                      <div>
                        <Input
                          placeholder="请输入来源表"
                          value={relation.from_table_name || tableName}
                          disabled
                          onChange={(e) => handleRelationChange(index, 'from_table_name', e.target.value)}
                        />
                      </div>
                      
                      {/* 来源字段 */}
                      <div>
                        <Select
                          placeholder="请选择来源字段"
                          value={relation.from_column_name}
                          onChange={(value) => handleRelationChange(index, 'from_column_name', value)}
                          allowClear
                          showSearch
                          filterOption={(input, option) =>
                            (option?.label?.toString() ?? '').toLowerCase().includes(input.toLowerCase())
                          }
                          loading={sourceColumnsLoading}
                        >
                          {sourceColumns.map(column => (
                            <Select.Option key={column.column_name} value={column.column_name}>
                              {column.column_name}
                            </Select.Option>
                          ))}
                        </Select>
                      </div>
                      
                      {/* 目标表 */}
                      <div>
                        <Select
                          placeholder="请选择目标表"
                          value={relation.to_table_name}
                          onChange={(value) => handleRelationChange(index, 'to_table_name', value)}
                          allowClear
                          showSearch
                          filterOption={(input, option) =>
                            (option?.label?.toString() ?? '').toLowerCase().includes(input.toLowerCase())
                          }
                          loading={targetTablesLoading}
                        >
                          {targetTables.map(tableName => (
                            <Select.Option key={tableName} value={tableName}>
                              {tableName}
                            </Select.Option>
                          ))}
                        </Select>
                      </div>
                      
                      {/* 目标表字段 */}
                      <div>
                        <Select
                          placeholder="请选择目标表字段"
                          value={relation.to_column_name}
                          onChange={(value) => handleRelationChange(index, 'to_column_name', value)}
                          allowClear
                          showSearch
                          filterOption={(input, option) =>
                            (option?.label?.toString() ?? '').toLowerCase().includes(input.toLowerCase())
                          }
                          loading={targetColumnsLoading}
                          disabled={!relation.to_table_name}
                        >
                          {targetColumnsMap[relation.to_table_name]?.map(column => (
                            <Select.Option key={column.column_name} value={column.column_name}>
                              {column.column_name}
                            </Select.Option>
                          )) || []}
                        </Select>
                      </div>
                      
                      {/* 类型 */}
                      <div className="flex items-center space-x-1">
                        <Select
                          placeholder="请选择类型"
                          value={relation.relation_type}
                          onChange={(value) => handleRelationChange(index, 'relation_type', value)}
                          style={{ width: '90%' }}
                          allowClear
                        >
                          {relationTypeOptions.map(option => (
                            <Select.Option key={option.value} value={option.value}>
                              {option.label}
                            </Select.Option>
                          ))}
                        </Select>
                        
                        {/* 删除按钮 */}
                        <Button
                          type="text"
                          icon={<MinusCircleOutlined />}
                          onClick={() => handleRemoveRelation(index)}
                          className="text-red-500 hover:text-red-700 flex-shrink-0 !m-0"
                          title="点击删除"
                        />
                      </div>
                    </div>
                  </div>
                ))}
              </div>
              
              {/* 空状态 */}
              {relations.length === 0 && (
                <div className="px-4 py-8 text-center text-gray-500">
                  暂无表关系，点击上方按钮添加
                </div>
              )}
            </div>
          </div>
        </Form.Item>
        
        {/* 操作按钮 */}
        <div className="flex justify-end space-x-3 pt-6 border-t border-gray-200">
          <Button onClick={onCancel}>
            取消
          </Button>
          <Button 
            type="primary" 
            onClick={handleSubmit}
            loading={updateLoading}
          >
            确认
          </Button>
        </div>
      </Form>
    </div>
  );
};

export default BasicInfoEditModal; 